package hn.cch.advanced.concurrent;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolExecutorDemo.class);


    /**
     * 获取线程池
     *
     * @return ThreadPoolExecutor
     */
    public ThreadPoolExecutor getThreadPoolExecutor() {
        return new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(4));
    }


    @Test
    public void testExecuteRunnable() {
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        threadPoolExecutor.execute(() -> {
            try {
                List<String> list = new ArrayList<>();
                Thread.sleep((long) (Math.random() * 10000));
            } catch (Exception e) {
                logger.error("", e);
            }
        });
        threadPoolExecutor.shutdown();
        ExecutorServiceDemo.complete(threadPoolExecutor);

    }


    @Test
    public void testSubmitCallable() {
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        Future<String> future = threadPoolExecutor.submit(() -> {
            try {
                Thread.sleep((long) (Math.random() * 10000));
            } catch (Exception e) {
                logger.error("", e);
            }
            return "";
        });
        threadPoolExecutor.shutdown();
        ExecutorServiceDemo.complete(threadPoolExecutor);

    }
}
